﻿using Authentication.Model.Interface;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Identifier;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Paging;
using Common.Service.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.ServiceCommand
{
    public class RetrieveGroupsServiceCommand : ProviderServiceCommand<IGroupProvider, RetrieveGroupsRequest, RetrieveGroupsResponse>
    {
        public RetrieveGroupsServiceCommand(IGroupProvider providers) : base(providers) { }

        protected override void Validate(RetrieveGroupsRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
        }

        protected override bool OnExecute(RetrieveGroupsResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0;
            List<GroupRecord> records = null;
            var applicationKey = Request.Header.ApplicationKey;
            if (Request.Page != null)
            {
                pageIndex = Request.Page.PageIndex ?? 0;
                pageSize = Request.Page.PageSize ?? 0;
            }
            var objects = Providers.SearchGroups(out totalRecord, Request.Header.ApplicationKey.Value, Request.Name, pageSize, pageIndex);
            if (objects != null)
            {
                records = objects.Select(x => new GroupRecord
                {
                    ApplicationKey = x.GuidKey,
                    GroupName = x.GroupNameEnglish,
                    GroupIdentifier = x.GroupId,
                    Description = x.Description,
                    //CreationDate = x.CreationDate,
                    //UpdateDate = x.UpdateDate
                }).ToList();
            }

            response.Records = records;
            response.Page = new PageRecord
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalRecords = totalRecord
            };
            return isSuccess;
        }
    }
}
